"""
日志系统集成入口
统一管理loguru和传统logging的集成
"""

import os
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

# 导入loguru配置
from app.core.loguru_config import setup_loguru_logging, get_logger, get_loguru_config
from app.middleware.loguru_middleware import setup_loguru_middleware


def setup_logging(environment: str = None, app_name: str = "fastapi-app", log_dir: str = None):
    """
    设置日志系统
    
    Args:
        environment: 环境类型 (development, testing, production)
        app_name: 应用名称
        log_dir: 日志目录路径
    
    Returns:
        Loguru配置对象
    """
    
    # 从环境变量获取默认值
    environment = environment or os.getenv("ENVIRONMENT", "development")
    app_name = app_name or os.getenv("APP_NAME", "fastapi-app")
    log_dir = log_dir or os.getenv("LOG_DIR", "./logs")
    
    # 设置loguru日志系统
    config = setup_loguru_logging(
        environment=environment,
        app_name=app_name,
        log_dir=log_dir
    )
    
    return config


def get_logging_config():
    """获取日志配置"""
    try:
        return get_loguru_config()
    except RuntimeError:
        # 如果尚未初始化，则进行初始化
        return setup_logging()


# 提供兼容性接口，方便从logging迁移到loguru
class LoggerCompat:
    """日志兼容性包装器，提供与logging类似的接口"""
    
    def __init__(self, name: str = None):
        self.logger = get_logger(name)
    
    def debug(self, msg: str, *args, **kwargs):
        """调试级别日志"""
        if args:
            msg = msg % args
        self.logger.debug(msg, **kwargs)
    
    def info(self, msg: str, *args, **kwargs):
        """信息级别日志"""
        if args:
            msg = msg % args
        self.logger.info(msg, **kwargs)
    
    def warning(self, msg: str, *args, **kwargs):
        """警告级别日志"""
        if args:
            msg = msg % args
        self.logger.warning(msg, **kwargs)
    
    def error(self, msg: str, *args, **kwargs):
        """错误级别日志"""
        if args:
            msg = msg % args
        self.logger.error(msg, **kwargs)
    
    def exception(self, msg: str, *args, **kwargs):
        """异常日志"""
        if args:
            msg = msg % args
        self.logger.exception(msg, **kwargs)
    
    def critical(self, msg: str, *args, **kwargs):
        """严重级别日志"""
        if args:
            msg = msg % args
        self.logger.critical(msg, **kwargs)


def getLogger(name: str = None) -> LoggerCompat:
    """获取日志记录器（兼容logging.getLogger接口）"""
    return LoggerCompat(name)


# 导出常用函数
__all__ = [
    'setup_logging',
    'get_logging_config',
    'getLogger',
    'get_logger',
    'setup_loguru_middleware',
    'LoggerCompat'
]